<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\Paginator;

class Base extends Model
{
    public $timestamps = false;
    
    /**
     * 对给定的查询进行分页-重写。
     * 考虑到性能问题，通常$columns我们不以*号为值。可传入需要查询的字段替代。
     *
     * @param  int|null  $perPage
     * @param  array  $columns
     * @param  string  $pageName
     * @param  int|null  $page
     * @return array
     *
     * @throws \InvalidArgumentException
     */
    public function paginate($perPage = null, $columns = ['*'], $page = null, $pageName = 'page'){
        $page = $page ?: Paginator::resolveCurrentPage($pageName);

        $perPage = $perPage ?: $this->model->getPerPage();

        $results = ($total = $this->toBase()->getCountForPagination())
            ? $this->forPage($page, $perPage)->get($columns)
            : $this->model->newCollection();
        $pages = ceil($total / $perPage);
        $result = ['total'=>$total,'current_page'=>$page,'per_page'=>$perPage,'pages'=>$pages,'list'=>$results];
        return $result;
    }
}
